#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <net/if.h>
#include <netdb.h>

int create_server(int proto)
{
	int fd = 0;
	int s_opt = 1;
	if (proto == AF_INET) {
		struct sockaddr_in addr;
		memset(&addr, 0, sizeof(addr));
		addr.sin_family = proto;
		addr.sin_addr.s_addr = INADDR_ANY;
		if (inet_pton(proto, "192.168.10.1", &addr.sin_addr) != 1) {
			perror("inet_pton 4");
			exit(0);
		}
		addr.sin_port = htons(8000);
		fd = socket(proto, SOCK_STREAM, IPPROTO_TCP);

		if (bind(fd, (void *)&addr, sizeof(addr)) < 0) {
			perror("bind 4 ");
			exit(0);
		}
		listen(fd, 5);
	} else {
		struct sockaddr_in6 addr;
		memset(&addr, 0, sizeof(addr));
		addr.sin6_family = proto;
		addr.sin6_addr = in6addr_any;
		if (inet_pton(proto, "fe80::baba:68ff:feac:dead", &addr.sin6_addr) != 1) {
			perror("inet_pton 6");
			exit(0);
		}
		addr.sin6_port = htons(8000);
		addr.sin6_scope_id = if_nametoindex("br0");
		fd = socket(proto, SOCK_STREAM, IPPROTO_TCP);
		//setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, &s_opt, sizeof(s_opt));
		if (bind(fd, (void *)&addr, sizeof(addr)) < 0) {
			perror("bind 6");
			exit(0);
			return 0;
		}
		listen(fd, 5);
	}

	if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (void *)&s_opt, sizeof(s_opt))) {
		perror("setsockopt");
		return 0;
	}
	return fd;
}

int resolve_name(const char *host)
{
	struct addrinfo hints, *res, *rp;
	memset(&hints, 0, sizeof(hints));
	hints.ai_family = AF_UNSPEC;
	hints.ai_socktype = SOCK_STREAM;
	hints.ai_protocol = IPPROTO_TCP;

	getaddrinfo(host, "80", &hints, &res);

	for (rp = res; rp; rp = rp->ai_next) {
		char hname[128], service[16];
		getnameinfo(rp->ai_addr, rp->ai_addrlen, hname, sizeof(hname), service, sizeof(service), NI_NUMERICHOST | NI_NUMERICSERV);
		printf("hname=%s\n", hname);
	}
	return 0;
}

int main()
{
	char cmd_buff[1024];
	snprintf(cmd_buff, sizeof(cmd_buff), "sed -i \"s/\\(.*<Value Name=\\\"aucIPv4Addr\\\".*Value=\\\"\\)\\(.*\\)\\(\\\"\\)/\\1%s\\3/\" %s", "192.168.141.1",
		 "/config/work/lastgood.xml"); /*lint !e606*/
	printf("cmd=%s\n", cmd_buff);
	snprintf(cmd_buff, sizeof(cmd_buff), "sed -i \"s/\\(.*<Value Name=\\\"aucMinAddr\\\".*Value=\\\"\\)\\(.*\\)\\(\\\"\\)/\\1%s\\3/\" %s", "192.168.141.10",
		 "/config/work/lastgood.xml"); /*lint !e606*/
	printf("cmd=%s\n", cmd_buff);
	snprintf(cmd_buff, sizeof(cmd_buff), "sed -i \"s/\\(.*<Value Name=\\\"aucMinAddr\\\".*Value=\\\"\\)\\(.*\\)\\(\\\"\\)/\\1%s\\3/\" %s", "192.168.141.254",
		 "/config/work/lastgood.xml"); /*lint !e606*/
	printf("cmd=%s\n", cmd_buff);
	resolve_name("www.rs6pro.cn");
	return 0;
}